<template>
  <div>
    
    
    <input type="file" @change="handleFileUpload" accept=".xlsx, .xls" />
    <button @click="sendData">计算</button>

    <table v-if="data.length">
      <thead>
        <tr>
          <th v-for="(header, index) in headers" :key="index">{{ header }}</th>
        </tr>
      </thead>

      <tbody>
        <tr v-for="(row, rowIndex) in data" :key="rowIndex">
          <td v-for="(cell, cellIndex) in row" :key="cellIndex">{{ cell }}</td>
        </tr>
      </tbody>
    </table>

  </div>
</template>

<script>
import * as XLSX from "xlsx";

import { EventBus } from "../event.js";

export default {
  data() {
    return {
      data: [],

      headers: [],
    };
  },

  methods: {
    handleFileUpload(event) {
      const file = event.target.files[0];

      const reader = new FileReader();

      reader.onload = (e) => {
        const binaryStr = e.target.result;

        const workbook = XLSX.read(binaryStr, { type: "binary" });

        // 读取第一个工作表

        const firstSheetName = workbook.SheetNames[0];

        const worksheet = workbook.Sheets[firstSheetName];

        // 将工作表转换为 JSON

        this.data = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        this.headers = this.data[0]; // 假设第一行是表头

        this.data = this.data.slice(1); // 其余行是数据

        // console.log(this.data);
      };

      reader.readAsBinaryString(file);
    },

    sendData() {
      EventBus.$emit("data-sent", this.data);
    },

    exportWithMinMax() {
      const newWorkbook = XLSX.utils.book_new();

      // 将原始数据写入 Sheet1

      const originalWorksheet = XLSX.utils.aoa_to_sheet([
        this.headers,
        ...this.data,
      ]);

      XLSX.utils.book_append_sheet(newWorkbook, originalWorksheet, "Sheet1");

      // 导出新的 Excel 文件

      XLSX.writeFile(newWorkbook);
    },
  },
};
</script>

<style scoped>
table {
  border-collapse: collapse;

  width: 100%;
}

th,
td {
  border: 1px solid #ddd;

  padding: 8px;
}
</style>
